package com.kinon.market.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.market.R;
import com.kinon.market.entity.RukuEntity;
import com.kinon.market.tools.HttpTools;
import com.kinon.market.tools.MyShowDialog;
import com.kinon.market.tools.MyToast;
import com.kinon.market.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;

import static com.kinon.market.R.layout.spinner;

/**
 * 入库
 */

public class RukuFragment extends Fragment implements OnClickListener {

    View iscatview = null;
    View jianpanview = null;

    String token;
    //	private TextView tv_amount;
    String str = "";
    String str2 = "应付账款 ";
    String tiaoma = "";
    int amount = 0;
    double total = 0.0;
    String data2;
    String id2;
    String type;
    /**
     * 供应商数组
     */
    JSONArray array3;
    String shuliang = "";
    /**
     * 商品信息的集合
     */
    ArrayList<RukuEntity> rukulist;
    RukuAdapter rukuAdapter;
    HttpTools toolModel = null;
    //	BigDecimal bd=new BigDecimal()
    DecimalFormat df = new DecimalFormat("#.00");
    /**
     * 数字按钮
     */
    private Button btn_9;
    private Button btn_8;
    private Button btn_7;
    private Button btn_6;
    private Button btn_5;
    private Button btn_4;
    private Button btn_3;
    private Button btn_2;
    private Button btn_1;
    private Button btn_0;
    private Button btn_shanchu;
    private Button btn_queren;
    /**
     * 提交
     */
    private Button btn_shoukuan;
    /**
     * 清空
     */
    private Button btn_qingkong;
    /**
     * 编码输入框
     */
    private EditText et_jiesuan;
    /**
     * 扫码输入框
     */
    private EditText et_id;
    /**
     * 商品数量
     */
    private TextView tv_amount;
    private ListView lv;
    /**
     * 选择日期的dialog
     */
    private Dialog diaDate;
    /**
     * 日期选择器
     */
    private DatePicker date_datepicker;
    /**
     * 选择日期的取消
     */
    private TextView dia_datecCancel;
    /**
     * 选择日期的确定
     */
    private TextView dia_dateDetermine;
    private Context mContext;
    /**
     * EditText监听
     */
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_id.getText().length() == 13) {
                getShangpininfo1(et_id.getText().toString());

            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ruku, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        initRes();
    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        et_id.requestFocus();

    }

    private void initRes() {
        SharedPreferences sp = getActivity().getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        lv = (ListView) getView().findViewById(R.id.lv);
        rukulist = new ArrayList<RukuEntity>();
        rukuAdapter = new RukuAdapter(getActivity(), rukulist);
        lv.setAdapter(rukuAdapter);
//		//		pull_dingdan.getRefreshableView().setSelection(offset);
//		lv.setDivider(null);
        et_id = (EditText) getView().findViewById(R.id.et_id);
        btn_9 = (Button) getView().findViewById(R.id.btn_9);
        btn_8 = (Button) getView().findViewById(R.id.btn_8);
        btn_7 = (Button) getView().findViewById(R.id.btn_7);
        btn_6 = (Button) getView().findViewById(R.id.btn_6);
        btn_5 = (Button) getView().findViewById(R.id.btn_5);
        btn_4 = (Button) getView().findViewById(R.id.btn_4);
        btn_3 = (Button) getView().findViewById(R.id.btn_3);
        btn_2 = (Button) getView().findViewById(R.id.btn_2);
        btn_1 = (Button) getView().findViewById(R.id.btn_1);
        btn_0 = (Button) getView().findViewById(R.id.btn_0);
        btn_shanchu = (Button) getView().findViewById(R.id.btn_shanchu);
        btn_queren = (Button) getView().findViewById(R.id.btn_queren);
        btn_shoukuan = (Button) getView().findViewById(R.id.btn_shoukuan);
        btn_qingkong = (Button) getView().findViewById(R.id.btn_qingkong);
        tv_amount = (TextView) getView().findViewById(R.id.tv_amount);

        et_jiesuan = (EditText) getView().findViewById(R.id.et_shuru);

        addOnClicik();
        getSuppliers();

        tv_amount.setText("共计" + amount + "件商品");
        et_jiesuan.setFocusable(false);
//		et_jiesuan.clearFocus();

        et_id.addTextChangedListener(watcher);

    }

    private void addOnClicik() {
        btn_9.setOnClickListener(this);
        btn_8.setOnClickListener(this);
        btn_7.setOnClickListener(this);
        btn_6.setOnClickListener(this);
        btn_5.setOnClickListener(this);
        btn_4.setOnClickListener(this);
        btn_3.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_1.setOnClickListener(this);
        btn_0.setOnClickListener(this);
        btn_shanchu.setOnClickListener(this);
        btn_queren.setOnClickListener(this);
        btn_shoukuan.setOnClickListener(this);
        btn_qingkong.setOnClickListener(this);

        btn_shanchu.setFocusable(false);
        btn_queren.setFocusable(false);
        btn_shoukuan.setFocusable(false);
        btn_qingkong.setFocusable(false);
        btn_shanchu.setFocusable(false);
        btn_9.setFocusable(false);
        btn_8.setFocusable(false);
        btn_7.setFocusable(false);
        btn_6.setFocusable(false);
        btn_5.setFocusable(false);
        btn_4.setFocusable(false);
        btn_3.setFocusable(false);
        btn_2.setFocusable(false);
        btn_1.setFocusable(false);
        btn_0.setFocusable(false);
    }

    @Override
    public void onClick(View view) {
        et_id.setFocusable(true);
        et_id.setFocusableInTouchMode(true);
        et_id.requestFocus();

        switch (view.getId()) {
            case R.id.btn_9:
                str = str + "9";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_8:
                str = str + "8";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_7:
                str = str + "7";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_6:
                str = str + "6";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_5:
                str = str + "5";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_4:
                str = str + "4";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_3:
                str = str + "3";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_2:
                str = str + "2";
                et_jiesuan.setText(str);
                btn_2.setTextColor(getActivity().getResources().getColor(R.color.goodsPrice));
                break;
            case R.id.btn_1:
                str = str + "1";
                et_jiesuan.setText(str);
                break;
            case R.id.btn_0:
                str = str + "0";
                et_jiesuan.setText(str);
                break;

            case R.id.btn_shanchu:
                if (str.length() == 0) {
                    return;
                } else {
                    str = str.substring(0, str.length() - 1);
                    et_jiesuan.setText(str);
                }
                break;
            case R.id.btn_queren:
                getShangpininfo2();
                break;
            case R.id.btn_shoukuan:
                if (NetWorkUtil.isNetwork(getActivity()) == false) {
                    Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (rukulist.size() == 0) {
                        Toast.makeText(getActivity(), "请添加商品！", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        if (array3 == null) {
                            Toast.makeText(getActivity(), "请重新加载该界面！", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            Tijiaodialog();
                        }
                    }
                }
                break;
            case R.id.btn_qingkong:
                rukulist.removeAll(rukulist);
                rukuAdapter.notifyDataSetChanged();
                amount = 0;
                tv_amount.setText("共计" + amount + "件商品");
                break;

        }

    }

    /**
     * 获取供应商信息
     */
    private void getSuppliers() {
        toolModel = new HttpTools(getActivity());
        toolModel.getSuppliers(token,
                new JsonGetsuppliers());
    }

    /**
     * 扫码获取商品信息
     */
    private void getShangpininfo1(String tiaoma) {
        et_id.requestFocus();
        synchronized (tiaoma) {

            toolModel = new HttpTools(getActivity());
            toolModel.bycode(token, tiaoma,
                    new JsonShangpin());
        }
    }

    /**
     * 输入条码获取商品信息
     */
    private void getShangpininfo2() {
        btn_queren.setEnabled(false);
        toolModel = new HttpTools(getActivity());
        toolModel.bycode(token, str,
                new JsonShangpin());

    }

    /**
     * 提交信息弹窗
     */
    private void Tijiaodialog() {
        getSuppliers();
        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        iscatview = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_tijiao, null);
        ImageButton ib_close = (ImageButton) iscatview.findViewById(R.id.ib_close);
        final Spinner spgongyi = (Spinner) iscatview.findViewById(R.id.sp_gongyingshang);
        final Spinner spinner2 = (Spinner) iscatview.findViewById(R.id.sp_fukuanfangshi);
        final EditText et_beizhu = (EditText) iscatview.findViewById(R.id.et_beizhu);

        Button btn_wancheng = (Button) iscatview.findViewById(R.id.btn_wancheng);
        et_id.clearFocus();
//		et_beizhu.requestFocus();
        et_beizhu.setFocusable(false);
//		et_beizhu.setFocusableInTouchMode(false);

        dialog.setContentView(iscatview);
        dialog.show();
        et_beizhu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                et_beizhu.requestFocus();
                et_beizhu.setFocusable(true);
                et_beizhu.setFocusableInTouchMode(true);
            }
        });
        /*供应商下拉列表*/
        ArrayList<String> list = new ArrayList<String>();
        final Hashtable<String, String> hnameids = new Hashtable<String, String>();
        try {
            for (int i = 0; i < array3.length(); i++) {
                JSONObject obj = array3.getJSONObject(i);
                ;
                list.add(obj.getString("name"));
                hnameids.put(obj.getString("name"), obj.getString("id"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ArrayAdapter adapter = new ArrayAdapter(getActivity(), spinner, list);
        //		TextView tv_tuanduizhifu=(TextView)findViewById(R.id.tv_spinner);
        //		tv_tuanduizhifu.setTextSize(32);
        adapter.setDropDownViewResource(R.layout.drop_select_item_layout_2);
        spgongyi.setAdapter(adapter);
        spgongyi.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                data2 = (String) spgongyi.getSelectedItem();
                //				sp v1 = (TextView)findViewById(android.R.layout.simple_list_item_1,id,tex);
                //				 v1.setTextColor(Color.BLACK);
                id2 = hnameids.get(data2);
                Log.i("zq", "团队id---" + id2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

//			private void Tuandui() {
        int layout = spinner;
        int array = R.array.fukuanfangshi;
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(), array, layout);
        /**设置下拉列表布局对象*/
        adapter2.setDropDownViewResource(R.layout.drop_select_item_layout_2);
        spinner2.setAdapter(adapter2);
        type = "0";
        spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                str2 = (String) spinner2.getSelectedItem();
                if (str2.equals("应付账款")) {
                    type = "0";
                } else if (str2.equals("现金支付")) {
                    type = "1";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
//			}

        ib_close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                et_beizhu.setFocusable(false);
                et_beizhu.setFocusableInTouchMode(false);
                et_beizhu.clearFocus();
                et_id.requestFocus();
                dialog.dismiss();
            }
        });
        btn_wancheng.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                et_beizhu.setFocusable(false);
                et_beizhu.setFocusableInTouchMode(false);
                et_beizhu.clearFocus();
                et_id.requestFocus();
                if (rukulist.size() == 0) {
                    Toast.makeText(getActivity(), "请添加入库商品", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    save(et_beizhu.getText().toString());
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 保存入库信息
     */
    private void save(String note) {
        //		btn_shoukuan.setEnabled(false);
        toolModel = new HttpTools(getActivity());
        Gson gson = new Gson(); // 实例化Gson对象
        String data = gson.toJson(rukulist);
        Log.e("zq", "JsonObject-------" + data);
        toolModel.rukusave(token, data, id2, type, note, new JsonSave());
    }

    /**
     * 提交入库信息
     */
    private void tijiao(String id) {
        toolModel = new HttpTools(getActivity());
        toolModel.rukuconfirm(token, id, new JsonTijiao());
    }

    /**
     * 弹出输入键盘
     */
    private void Jianpandialog(final int index, final TextView Text,
                               final TextView textView) {

        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		dialog.setCanceledOnTouchOutside(false);
        jianpanview = LayoutInflater.from(getActivity()).inflate(
                R.layout.dialog_jianpan, null);
        Button btn_9 = (Button) jianpanview.findViewById(R.id.btn_9);
        Button btn_8 = (Button) jianpanview.findViewById(R.id.btn_8);
        Button btn_7 = (Button) jianpanview.findViewById(R.id.btn_7);
        Button btn_6 = (Button) jianpanview.findViewById(R.id.btn_6);
        Button btn_5 = (Button) jianpanview.findViewById(R.id.btn_5);
        Button btn_4 = (Button) jianpanview.findViewById(R.id.btn_4);
        Button btn_3 = (Button) jianpanview.findViewById(R.id.btn_3);
        Button btn_2 = (Button) jianpanview.findViewById(R.id.btn_2);
        Button btn_1 = (Button) jianpanview.findViewById(R.id.btn_1);
        Button btn_0 = (Button) jianpanview.findViewById(R.id.btn_0);
        Button btn_00 = (Button) jianpanview.findViewById(R.id.btn_00);
        Button btn_dian = (Button) jianpanview.findViewById(R.id.btn_dian);
        Button btn_wancheng = (Button) jianpanview.findViewById(R.id.btn_wancheng);
        Button btn_qingchu = (Button) jianpanview.findViewById(R.id.btn_qingchu);
        final TextView tv_shuliang = (TextView) jianpanview.findViewById(R.id.tv_amount);
//		final String shuliang="";
        if (textView == null) {
            btn_00.setText(".");
        } else {
            btn_00.setText("00");
        }
        dialog.setContentView(jianpanview);
        dialog.show();

        btn_9.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "9";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_8.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "8";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_7.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "7";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_6.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "6";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_5.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "5";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_4.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "4";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "3";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "2";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "1";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_0.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = shuliang + "0";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_00.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (textView == null) {
                    shuliang = shuliang + ".";
                } else {
                    shuliang = shuliang + "00";
                }

                tv_shuliang.setText(shuliang);
            }
        });
        btn_dian.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (shuliang.length() == 0) {
                    return;
                } else {
                    shuliang = shuliang.substring(0, shuliang.length() - 1);
                    tv_shuliang.setText(shuliang);
                }
            }
        });

        btn_qingchu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                shuliang = "";
                tv_shuliang.setText(shuliang);
            }
        });
        btn_wancheng.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (textView == null) {
                    try {
                        if (shuliang.equals("")) {
                            Toast.makeText(getActivity(), "请输入价格!", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (Double.parseDouble(shuliang) == 0.0) {
                            Toast.makeText(getActivity(), "请确认过价格是0", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            double price = Double.parseDouble(shuliang);
//						amount=amount-Integer.parseInt(Text.getText().toString())+Integer.parseInt(shuliang);
//						tv_amount.setText("共计"+amount+"件商品");
                            Text.setText(price + "");
                            rukulist.get(index).setCostprice1(price);
//						rukulist.get(index).setTotalprice(""+Integer.parseInt(shuliang)*Double.parseDouble(rukulist.get(index).getPrice()));
//						textView.setText("￥"+Integer.parseInt(shuliang)*Double.parseDouble(rukulist.get(index).getPrice()));
                            et_id.requestFocus();
                            shuliang = "";
//					et_id.requestFocus();
                            dialog.dismiss();
                        }
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "请确认你输入的价格", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    if (shuliang.equals("")) {
                        Toast.makeText(getActivity(), "请输入数量!", Toast.LENGTH_SHORT).show();
                        return;
                    } else if (Integer.parseInt(shuliang) == 0) {
                        Toast.makeText(getActivity(), "数量必须大于0!", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        amount = amount - Integer.parseInt(Text.getText().toString()) + Integer.parseInt(shuliang);
                        tv_amount.setText("共计" + amount + "件商品");
                        Text.setText(shuliang);
                        rukulist.get(index).setNewamount(shuliang);
                        rukulist.get(index).setTotalprice("" + Integer.parseInt(shuliang) * Double.parseDouble(rukulist.get(index).getPrice()));
                        textView.setText("￥" + Integer.parseInt(shuliang) * Double.parseDouble(rukulist.get(index).getPrice()));
                        et_id.requestFocus();
                        shuliang = "";
//					et_id.requestFocus();
                        dialog.dismiss();
                    }

                }


            }
        });
    }

    private class JsonShangpin extends JsonHttpResponseHandler {
        boolean flag = false;
        int index;

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            et_id.setText("");
            try {
                Log.i("info", "商品列表----" + response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONObject data = response.getJSONObject("data");
                    String id = data.getString("id");
                    String code1 = data.getString("code");
                    String name = data.getString("name");
                    String purchaseprice = data.getString("purchaseprice");
                    Double costprice1 = data.getDouble("costprice1");

                    for (int i = 0; i < rukulist.size(); i++) {
                        if (rukulist.get(i).getCode().equals(code1)) {
//							shangpinlist.get(i).setAmount(""+(Integer.parseInt(shangpinlist.get(i).getAmount())+1));
                            index = i;
                            flag = true;
                            continue;
                        }/*else {
                            flag=false;
						}*/
                    }
                    if (flag == true) {
                        rukulist.get(index).setNewamount("" + (Integer.parseInt(rukulist.get(index).getNewamount()) + 1));
                        rukulist.get(index).setTotalprice("" + (Double.parseDouble(rukulist.get(index).getTotalprice()) + Double.parseDouble
                                (rukulist.get(index).getPrice())));
                    } else {
                        rukulist.add(0, new RukuEntity(id, code1, name, purchaseprice, costprice1, "1", purchaseprice, "", "1"));
                    }
                    rukuAdapter = new RukuAdapter(getActivity(), rukulist);
                    lv.setAdapter(rukuAdapter);
                    lv.setDivider(null);
//					rukuAdapter.notifyDataSetChanged();
                    btn_queren.setEnabled(true);
                    str = "";
                    et_jiesuan.setText(str);
                    amount = amount + 1;
                    tv_amount.setText("共计" + amount + "件商品");
                } else {
                    btn_queren.setEnabled(true);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            et_id.setText("");
            Toast.makeText(getActivity(), "网络请求超时", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 供应商信息
     */
    private class JsonGetsuppliers extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);

            try {
//				Log.i("info","供应商列表----"+response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    array3 = response.getJSONArray("data");
                } else {
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(getActivity(), "网络请求超时", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 商品适配器
     */
    public class RukuAdapter extends BaseAdapter {
        Context context;
        ArrayList<RukuEntity> rukulist;
        HttpTools httpTools = null;
        int num;
        int num2;
        double num3;

        public RukuAdapter(Context context, ArrayList<RukuEntity> rukulist) {
            super();
            this.context = context;
            this.rukulist = rukulist;
        }

        //		public void add(RukuEntity rukuEntity) {
//			// TODO Auto-generated method stub
//
//		}
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return rukulist.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return rukulist.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            final ViewHandle handle;
            if (view == null) {
                handle = new ViewHandle();
                view = LayoutInflater.from(context).inflate(R.layout.item_rukushangpin, null);
                handle.tv_tiaoma = (TextView) view.findViewById(R.id.tv_tiaoma);
                handle.tv_name = (TextView) view.findViewById(R.id.tv_name);
                handle.ib_jia = (ImageButton) view.findViewById(R.id.ib_jia2);
                handle.ib_jian = (ImageButton) view.findViewById(R.id.ib_jian2);
                //				handle.tv_oldamount=(TextView)view.findViewById(R.id.tv_yuanyou);
                handle.tv_amount2 = (TextView) view.findViewById(R.id.tv_amount2);
                handle.tv_riqi = (TextView) view.findViewById(R.id.tv_shengchanriqi);
                handle.et_purchasePrice = (TextView) view.findViewById(R.id.et_purchasePrice);
                handle.tv_jiage = (TextView) view.findViewById(R.id.tv_jiage);

                handle.tv_xiaoji = (TextView) view.findViewById(R.id.tv_xiaoji);
                view.setTag(handle);
            } else {
                handle = (ViewHandle) view.getTag();
            }
            handle.tv_tiaoma.setText(rukulist.get(position).getCode());
            handle.tv_name.setText(rukulist.get(position).getName());
            handle.tv_amount2.setText(rukulist.get(position).getNewamount());
            handle.tv_jiage.setText("￥" + rukulist.get(position).getPrice());
            handle.et_purchasePrice.setText(rukulist.get(position).getCostprice1() + "");
            handle.tv_xiaoji.setText("￥" + df.format(Double.parseDouble(rukulist.get(position).getTotalprice())));
            handle.tv_riqi.setText(rukulist.get(position).getDate_production());
            handle.tv_riqi.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialogDatePicker(position, handle.tv_riqi);
                }
            });
            handle.tv_amount2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Jianpandialog(position, handle.tv_amount2, handle.tv_xiaoji);
                }
            });
            handle.et_purchasePrice.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Jianpandialog(position, handle.et_purchasePrice, null);
                }
            });

            handle.ib_jia.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int goodsNum = Integer.parseInt(handle.tv_amount2.getText().toString());
                    goodsNum++;
                    handle.tv_amount2.setText("" + goodsNum);
                    rukulist.get(position).setNewamount("" + goodsNum);
                    String total = df.format(Double.parseDouble(rukulist.get(position).getPrice())
                            * Integer.parseInt(handle.tv_amount2.getText().toString()));
                    handle.tv_xiaoji.setText("￥" + total);
                    rukulist.get(position).setTotalprice("" + total);
                    amount = amount + 1;
//					total=total+Double.parseDouble(pandianList.get(position).getPrice());
//					btn_shoukuan.setText("收款"+"￥"+total);
                    tv_amount.setText("共计" + amount + "件商品");
                }
            });
            handle.ib_jian.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    int goodsNum = Integer.parseInt(handle.tv_amount2.getText().toString());
                    goodsNum--;
                    if (goodsNum <= 0) {

                        handle.tv_amount2.setText("" + goodsNum);
                        rukulist.remove(position);
                        rukuAdapter.notifyDataSetChanged();
                        amount = amount - 1;
                        tv_amount.setText("共计" + amount + "件商品");
                        return;
                    }
                    handle.tv_amount2.setText("" + goodsNum);
                    rukulist.get(position).setNewamount("" + goodsNum);
                    String total = df.format(Double.parseDouble(rukulist.get(position).getPrice())
                            * Integer.parseInt(handle.tv_amount2.getText().toString()));
                    handle.tv_xiaoji.setText("￥" + total);
                    rukulist.get(position).setTotalprice("" + total);
                    amount = amount - 1;
//					total=total-Double.parseDouble(pandianList.get(position).getPrice());
                    tv_amount.setText("共计" + amount + "件商品");
//
                }
            });


            return view;
        }

        /**
         * 选择生产日期
         */
        private void dialogDatePicker(final int index, final TextView textView) {
            diaDate = new Dialog(getActivity());
            diaDate.requestWindowFeature(getActivity().getWindow().FEATURE_NO_TITLE);
            View pickerview = LayoutInflater.from(getActivity()).inflate(
                    R.layout.dialog_datepicker, null);
            date_datepicker = (DatePicker) pickerview
                    .findViewById(R.id.date_datepicker);
            dia_datecCancel = (TextView) pickerview
                    .findViewById(R.id.tv_datecCancel);
            dia_dateDetermine = (TextView) pickerview
                    .findViewById(R.id.tv_dateDetermine);
            diaDate.setContentView(pickerview);
            diaDate.show();
            dia_datecCancel.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    diaDate.dismiss();
                    et_id.requestFocus();
                }
            });
            dia_dateDetermine.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    String month = date_datepicker.getMonth() + 1 >= 10 ? date_datepicker
                            .getMonth() + 1 + ""
                            : "0" + (date_datepicker.getMonth() + 1);
                    String date = date_datepicker.getDayOfMonth() >= 10 ? date_datepicker
                            .getDayOfMonth() + ""
                            : "0" + date_datepicker.getDayOfMonth();

                    int select = Integer.parseInt(date_datepicker.getYear() + month
                            + date);

//					}
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
                    Date curDate = new Date(System.currentTimeMillis());
                    int curdate = Integer.parseInt(format.format(curDate));
                    if (select > curdate) {
                        MyToast.mToast(getActivity(), "您选择的时间大于今天的时间");
                        return;
                    }
//				Log.e("lh", "curdate--" + curdate);
                    textView.setText(date_datepicker.getYear() + "-" + month
                            + "-" + date);
                    rukulist.get(index).setDate_production(date_datepicker.getYear() + "-" + month
                            + "-" + date);
                    diaDate.dismiss();
                    et_id.requestFocus();
                }
            });
        }

        class ViewHandle {
            /**
             * 条码
             */
            TextView tv_tiaoma;
            /**
             * 商品名
             */
            TextView tv_name;
            /**
             * 加
             */
            ImageButton ib_jia;
            /**
             * 数量
             */
            TextView tv_amount2;
            /**
             * 减
             */
            ImageButton ib_jian;
            /**
             * 生产日期
             */
            TextView tv_riqi;
            /**
             * 价格
             */
            TextView tv_jiage;
            /**
             * 进货价
             */
            TextView et_purchasePrice;
            /**
             * 小计
             */
            TextView tv_xiaoji;
        }
    }

    private class JsonSave extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(getActivity(), "入库提交中....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            try {
//				Log.i("info","保存订单----"+response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    btn_shoukuan.setEnabled(true);
                    String data = response.getString("data");
                    tijiao(data);
                    rukulist.removeAll(rukulist);
                    rukuAdapter.notifyDataSetChanged();
                    //					total=0.0;
                    amount = 0;
                    tv_amount.setText("共计" + amount + "件商品");
                    //					btn_shoukuan.setText("收款");
//					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                } else {
                    btn_shoukuan.setEnabled(true);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private class JsonTijiao extends JsonHttpResponseHandler {
        //		@Override
//		public void onStart() {
//			MyShowDialog.showLoadingDialog(getActivity(), "入库提交中....");
//			super.onStart();
//		}
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
//			MyShowDialog.closeLoadingDialog();
            try {
                Log.i("info", "提交订单----" + response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                } else {
//					btn_shoukuan.setEnabled(true);
                    Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }


}
